#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

/**
 * @brief 使用 acq_rel 进行原子读-改-写以同步多线程计数。
 */
int main() {
  std::atomic<int> counter{0};
  constexpr int kThreads = 4;
  constexpr int kIncrementsPerThread = 10'000;

  auto worker = [&]() {
    for (int i = 0; i < kIncrementsPerThread; ++i) {
      counter.fetch_add(1, std::memory_order_acq_rel);  ///< 同时获取/发布。
    }
  };

  std::vector<std::thread> threads;
  threads.reserve(kThreads);
  for (int i = 0; i < kThreads; ++i) {
    threads.emplace_back(worker);
  }
  for (auto& t : threads) {
    t.join();
  }

  std::cout << "acq_rel counter: " << counter.load(std::memory_order_acquire) << '\n';
  return 0;
}